﻿using NewRen.Models.ViewModel;
using NewRen.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using NewRen.Schemas;
using System.Web.Hosting;
using System.IO;
using NewRen.Models.DataModel;
using NewRen.Helpers;
using System.Net;
using NewRen.Log4net;

namespace NewRen.Controllers
{
    public class UserGroupController : BaseController
    {
        //商户首页
        [HttpGet]
        public ActionResult Index(string City, string Industry, int p = 0)
        {
            try
            {
                IEnumerable<UserGroup> query = db.UserGroups.AsEnumerable();
                if (!string.IsNullOrEmpty(City))
                {
                    query = query.Where(c => c.City == City);
                }
                if (!string.IsNullOrEmpty(Industry))
                {
                    query = query.Where(c => c.Industry == Industry);
                }
                ViewBag.City = (City == null ? "" : City);

                ViewBag.Industry = (Industry == null ? "" : Industry);
                query = query.OrderByDescending(x => x.Priority);
                ViewBag.PageInfo = PagerHelper.Do(ref query, 50, p);

                List<City> Cities = new List<City>();
                List<Industry> Industries = new List<Industry>();
                List<City> CitiesMore = new List<City>();
                List<Industry> INdustriesMore = new List<Industry>();

                Cities = db.Cities.DistinctBy(c => c.CityName).Take(20).ToList();
                CitiesMore = db.Cities.DistinctBy(c => c.CityName).Skip(20).ToList();
                Industries = db.Industries.DistinctBy(i => i.IndustryName).Take(15).ToList();
                INdustriesMore = db.Industries.DistinctBy(i => i.IndustryName).Skip(15).ToList();

                ViewBag.Cities = Cities;
                ViewBag.CitiesMore = CitiesMore;
                ViewBag.Industries = Industries;
                ViewBag.IndustriesMore = INdustriesMore;
                return View(query);
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("商户首页出错", HttpHelper.GetIPAddress()), ex);
                return Redirect("/Shared/info?msg=数据异常，请稍后重试");
            }
        }

        #region 牛棚信息展示
        /// <summary>
        /// 牛棚信息展示页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [Schemas.AccessShowUserGroup]
        public ActionResult Show(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            UserGroup usergroup = db.UserGroups.Find(id);
            if (usergroup == null)
            {
                return HttpNotFound();
            }
            else
            {
                ViewBag.User = new vUserGroup(usergroup);
            }
            return View();
        }
        #endregion

        #region 牛棚宣传图片管理
        /// <summary>
        /// 牛棚宣传图片界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessShowUserGroup]
        public ActionResult GroupPictureShow(int id)
        {
            UserGroup group = db.UserGroups.Find(id);
            ViewBag.Group = group;
            if (group != null)
            {
                ViewBag.Images = db.Images.Where(c => c.TID == id).Where(c => c.ImageType == ImageType.UserGroup).ToList();
            }
            else
            {
                return HttpNotFound();
            }
            return View();
        }
        /// <summary>
        /// 牛棚宣传图片增加
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [Schemas.AccessShowUserGroup]
        public ActionResult AddGroupPicture(UserGroup model, int id, HttpPostedFileBase file)
        {
            UserGroup group = db.UserGroups.Find(model.ID);
            if (group == null)
            {
                return HttpNotFound();
            }
            else
            {
                if (file != null)
                {
                    string random = Helpers.DateHelper.GetTimeStamp();
                    Images product_img = new Images();
                    product_img.TID = model.ID;
                    product_img.ImageType = ImageType.UserGroup;
                    product_img.ContentType = file.ContentType;
                    product_img.Time = DateTime.Now;
                    string root = "~/GroupFile/" + group.GroupName + "/";
                    var phicyPath = HostingEnvironment.MapPath(root);
                    Directory.CreateDirectory(phicyPath);
                    file.SaveAs(phicyPath + random + file.FileName);
                    product_img.Path = "/GroupFile/" + group.GroupName + "/" + random + file.FileName;
                    db.Images.Add(product_img);
                    db.SaveChanges();
                    return Redirect("/UserGroup/GroupPictureShow/" + group.ID);
                }
                else
                {
                    ModelState.AddModelError("", "图片信息有问题，请重新上传");
                    return Redirect("/UserGroup/GroupPictureShow/" + group.ID);
                }
            }
        }

        /// <summary>
        /// 商户宣传图片删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public ActionResult DelGroupPicture(int id)
        {
            Images image = new Images();
            image = db.Images.Find(id);
            if (image != null)
            {
                var phicyPath = HostingEnvironment.MapPath(image.Path);
                System.IO.File.Delete(phicyPath);
                db.Images.Remove(image);
                db.SaveChanges();
                return Content("ok");
            }
            else
            {
                return Content("err");
            }
        }
        #endregion

        #region 牛棚信息修改
        /// <summary>
        /// 牛棚信息修改页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [Schemas.AccessShowUserGroup]
        public ActionResult Edit(int id)
        {
            UserGroup user = db.UserGroups.Find(id);
            if (user != null)
            {
                ViewBag.User = user;
                ViewBag.Industry = db.Industries.ToList();
                ViewBag.Cities = db.Cities.ToList();
            }
            else
            {
                return HttpNotFound();
            }
            return View();
        }
        /// <summary>
        /// 牛棚信息修改操作
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        [Schemas.AccessShowUserGroup]
        public ActionResult Edit(int id, UserGroup model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    UserGroup User = db.UserGroups.Find(model.ID);
                    ViewBag.user = User;
                    User.GroupName = model.GroupName;
                    User.Description = model.Description;
                    User.Phone = model.Phone;
                    User.Address = model.Address;
                    User.WhatApp = model.WhatApp;
                    User.Email = model.Email;
                    User.City = model.City;
                    User.Weibo = model.Weibo;
                    User.Industry = model.Industry;
                    db.SaveChanges();
                    return RedirectToAction("Show/" + User.ID);
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("牛棚信息修改出错", HttpHelper.GetIPAddress()), ex);
                    ModelState.AddModelError("", "修改信息有误，请审核后再提交");
                }
            }
            else
            {
                ModelState.AddModelError("", "修改信息有误，请审核后再提交");
            }
            ViewBag.User = db.UserGroups.Find(model.ID);
            ViewBag.Industry = db.Industries.ToList();
            ViewBag.Cities = db.Cities.ToList();
            return View();
        }
        #endregion

        #region 修改个人密码
        /// <summary>
        /// 修改牛棚密码界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        [Schemas.AccessShowUserGroup]
        public ActionResult PwdEdit(int id)
        {
            UserGroup group = db.UserGroups.Find(id);
            if (group == null)
            {
                return HttpNotFound();
            }
            else
            {
                ViewBag.Group = new vPwdEdit(group);
                return View();
            }
        }

        /// <summary>
        /// 修改牛棚密码信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Schemas.AccessShowUserGroup]
        public ActionResult PwdEdit(vPwdEdit model, int id)
        {
            UserGroup user = db.UserGroups.Find(model.ID);
            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(model.Password))
                {
                    string Password = Helpers.Encryt.GetMD5(model.Password);
                    if (!user.LoginPassword.Equals(Password))
                    {
                        ModelState.AddModelError("", "您输入原始密码错误！");
                    }
                    else
                    {
                        try
                        {
                            user.LoginPassword = Helpers.Encryt.GetMD5(model.PasswordNew);
                            db.SaveChanges();
                            return RedirectToAction("Show/" + user.ID);
                        }
                        catch (Exception ex)
                        {
                            log.Error(new LogContent("修改牛棚密码信息出错", HttpHelper.GetIPAddress()), ex);
                            ModelState.AddModelError("", "密码信息保存出现问题，请重试！");
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "原始密码不能为空！");
                }
            }
            else
            {
                ModelState.AddModelError("", "信息填写错误！");
            }
            UserGroup group = db.UserGroups.Find(model.ID);
            ViewBag.Group = new vPwdEdit(group);
            return View();
        }

        #endregion

        #region 修改图像
        /// <summary>
        /// 显示图像
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [Schemas.AccessShowUserGroup]
        public ActionResult PictureEdit(int id)
        {
            UserGroup user = new UserGroup();
            user = db.UserGroups.Find(id);
            ViewBag.User = user;
            return View();
        }
        /// <summary>
        /// 修改头像
        /// </summary>
        /// <param name="model"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Schemas.AccessShowUserGroup]
        public ActionResult PictureEdit(vEdit model, int id, HttpPostedFileBase file)
        {
            UserGroup user = db.UserGroups.Find(model.ID);
            try
            {
                if (file != null)
                {
                    System.IO.Stream stream = file.InputStream;
                    byte[] buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, (int)stream.Length);
                    stream.Close();
                    model.Picture = buffer;
                    user.Picture = model.Picture;
                }
                else
                {
                    user.Picture = model.Picture;
                }
                db.SaveChanges();
                return RedirectToAction("Show/" + user.ID);
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("修改头像出错", HttpHelper.GetIPAddress()), ex);
                return View(user);
            }
        }
        #endregion

        #region 显示头像
        /// <summary>
        /// 显示头像
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ShowPicture(int id)
        {
            UserGroup user = new UserGroup();
            user = db.UserGroups.Find(id);
            if (user != null)
            {
                return File(user.Picture, "image/jpg");
            }
            else
            {
                return File("/Images/userphoto.png", "image/jpg");
            }
        }
        #endregion

        #region 牛人管理
        /// <summary>
        /// 牛人管理页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessShowUserGroup]
        public ActionResult UserManager(int id)
        {
            UserGroup group = db.UserGroups.Find(id);
            if (group == null)
            {
                return HttpNotFound();
            }
            else
            {
                ViewBag.UserGroup = group;
                return View();
            }
        }
        #endregion

        #region 牛人列表
        /// <summary>
        /// 获取牛人列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult getUser(int page, int id)
        {
            int index = page * 12;
            List<User> userlist = db.Users.Where(c => c.UserGroupID == id).OrderByDescending(c => c.AddTime).Skip(index).Take(12).ToList();
            AjaxModel ajaxModel = new AjaxModel();
            try
            {
                if (userlist.Count == 0)
                {
                    ajaxModel.Data = "";
                    ajaxModel.Statu = "end";
                    ajaxModel.Msg = "数据加载完";
                }
                else
                {
                    ajaxModel.Data = userlist;
                    ajaxModel.Statu = "ok";
                    ajaxModel.Msg = "加载成功";
                }
            }
            catch (Exception ex)
            {
                log.Error(new LogContent("牛人列表出错", HttpHelper.GetIPAddress()), ex);
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "获取失败";
            }
            return Json(ajaxModel);
        }
        #endregion

        #region 增加牛人
        /// <summary>
        /// 增加牛人界面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [Schemas.AccessShowUserGroup]
        public ActionResult AddUser(int id)
        {
            UserGroup group = db.UserGroups.Find(id);
            if (group == null)
            {
                return HttpNotFound();
            }
            ViewBag.UserGroup = group;
            return View();
        }
        /// <summary>
        /// 增加牛人操作
        /// </summary>
        /// <param name="model"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [Schemas.AccessShowUserGroup]
        [ValidateAntiForgeryToken]
        public ActionResult AddUser(User model, int id)
        {
            ViewBag.UserGroup = db.UserGroups.Find(id);
            if (ModelState.IsValid)
            {
                var User = new User();
                User = db.Users.Where(u => u.UserName == model.UserName).FirstOrDefault();
                if (User == null)
                {
                    User user1 = db.Users.Where(u => u.Phone == model.Phone).FirstOrDefault();
                    if (user1 == null)
                    {
                        try
                        {
                            User = new Models.User();
                            User.UserName = model.UserName;
                            User.Password = Helpers.Encryt.GetMD5(model.Password);
                            User.UserGroupID = model.UserGroupID;
                            User.Phone = model.Phone;
                            User.AddTime = DateTime.Now;
                            db.Users.Add(User);
                            db.SaveChanges();
                            return RedirectToAction("UserManager/" + id);
                        }
                        catch (Exception ex)
                        {
                            log.Error(new LogContent("增加牛人操作出错", HttpHelper.GetIPAddress()), ex);
                            ModelState.AddModelError("", "信息保存出现问题，请重试！");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "该手机号已经存在！");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "该用户名已经存在！");
                }
            }
            else
            {
                ModelState.AddModelError("", "信息填写错误请重新填写！");
            }
            ViewBag.UserGroup = db.UserGroups.Find(id);
            return View();
        }
        /// <summary>
        /// 测试用户名
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CheckUserName(string username)
        {
            AjaxModel ajaxmodel = new AjaxModel();
            var user = new Models.User();
            try
            {
                user = db.Users.Where(u => u.UserName == username).FirstOrDefault();
                if (user == null)
                {
                    ajaxmodel.Statu = "ok";
                    ajaxmodel.Msg = "用户名可用";
                }
                else
                {
                    ajaxmodel.Statu = "err";
                    ajaxmodel.Msg = "用户名重复";
                }
            }
            catch (Exception ex)
            {
                ajaxmodel.Statu = "err";
                log.Error(new LogContent("测试用户名出错", HttpHelper.GetIPAddress()), ex);
                ajaxmodel.Msg = "数据异常";
            }
            return Json(ajaxmodel);
        }
        /// <summary>
        /// 手机号检测
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CheckPhone(string phone)
        {
            AjaxModel ajaxmodel = new AjaxModel();
            var user = new Models.User();
            user = db.Users.Where(u => u.Phone == phone).FirstOrDefault();
            if (user == null)
            {
                ajaxmodel.Statu = "ok";
                ajaxmodel.Msg = "手机号可用";
            }
            else
            {
                ajaxmodel.Statu = "err";
                ajaxmodel.Msg = "手机号已注册，请替换";
            }
            return Json(ajaxmodel);
        }
        #endregion

        #region 展示牛人
        /// <summary>
        /// 牛人展示页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Schemas.AccessUserGroupEditUser]
        public ActionResult UserShow(int id)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return Redirect("/Shared/Info?msg=该牛人不存在，请不要不合理操作");
            }
            else
            {
                ViewBag.User = new vUser(user);
                ViewBag.UserGroup = db.UserGroups.Find(user.UserGroupID);
                return View();
            }
        }
        #endregion

        #region 删除牛人
        /// <summary>
        /// 删除牛人信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [Schemas.AccessUserGroupEditUser]
        [ValidateSID]
        public ActionResult UserDelete(int id)
        {
            User user = new User();
            user = db.Users.Find(id);
            if (user == null)
            {
                return Content("err");
            }
            else
            {
                db.Users.Remove(user);
                db.SaveChanges();
                return Content("ok");
            }
        }
        #endregion

        #region 修改牛人
        /// <summary>
        /// 修改牛人界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        [Schemas.AccessUserGroupEditUser]
        public ActionResult UserEdit(int id)
        {
            User user = new User();
            user = db.Users.Find(id);
            if (user == null)
            {
                return Redirect("/Shared/Info?msg=该牛人不存在，请不要不合理操作");
            }
            else
            {
                try
                {
                    ViewBag.User = user;
                    ViewBag.UserGroup = db.UserGroups.Find(user.UserGroupID);
                    List<SelectListItem> ListSex = new List<SelectListItem>();
                    ListSex.Add(new SelectListItem { Text = "女", Value = "0", Selected = (user.SexAsInt == 0 ? true : false) });
                    ListSex.Add(new SelectListItem { Text = "男", Value = "1", Selected = (user.SexAsInt == 1 ? true : false) });
                    ViewBag.Jobs = db.Jobs.ToList();
                    ViewBag.Cities = db.Cities.ToList();
                    ViewBag.Sex = ListSex;
                    return View();
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent("修改牛人界面出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/UserGroup/UserEdit/" + id);
                }
            }
        }
        /// <summary>
        /// 修改牛人信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [Schemas.AccessUserGroupEditUser]
        [ValidateAntiForgeryToken]
        public ActionResult UserEdit(vEdit model, int id)
        {
            User user = db.Users.Find(model.ID);
            if (user == null)
            {
                return Redirect("/Shared/Info?msg=该牛人不存在，请不要不合理操作");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        ViewBag.user = user;
                        user.SexAsInt = model.SexAsInt;
                        user.Address = model.Address;
                        user.Birthday = model.Birthday;
                        user.Email = model.Email;
                        user.RealName = model.RealName;
                        user.QQ = model.QQ;
                        user.WhatApp = model.WhatApp;
                        user.Job = model.Job;
                        user.City = model.City;
                        user.District = model.District;
                        user.Town = model.Town;
                        user.Description = model.Description;
                        db.SaveChanges();
                        return RedirectToAction("UserShow/" + user.ID);
                    }
                    catch (Exception ex)
                    {
                        log.Error(new LogContent("修改牛人出错", HttpHelper.GetIPAddress()), ex);
                        ModelState.AddModelError("", "保存修改信息出现错误，请重试!");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "修改的信息输入错误!");
                }
                ViewBag.User = user;
                ViewBag.UserGroup = db.UserGroups.Find(user.UserGroupID);
                List<SelectListItem> ListSex = new List<SelectListItem>();
                ListSex.Add(new SelectListItem { Text = "女", Value = "0", Selected = (user.SexAsInt == 0 ? true : false) });
                ListSex.Add(new SelectListItem { Text = "男", Value = "1", Selected = (user.SexAsInt == 1 ? true : false) });
                ViewBag.Jobs = db.Jobs.ToList();
                ViewBag.Cities = db.Cities.ToList();
                ViewBag.Sex = ListSex;
                return View();
            }
        }
        #endregion

        #region 牛人密码修改
        /// <summary>
        /// 牛人密码修改界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        [Schemas.AccessUserGroupEditUser]
        public ActionResult UserPwdEdit(int id)
        {
            User user = db.Users.Find(id);
            if (user == null)
            {
                return Redirect("/Shared/Info?msg=该牛人不存在，请不要不合理操作");
            }
            else
            {
                ViewBag.user = new vPwdEdit(user);
                ViewBag.UserGroup = db.UserGroups.Find(user.UserGroupID);
                return View();
            }
        }
        /// <summary>
        /// 牛人密码修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [Schemas.AccessUserGroupEditUser]
        public ActionResult UserPwdEdit(vPwdEdit model, int id)
        {
            User user = db.Users.Find(model.ID);
            if (user == null)
            {
                return Redirect("/Shared/Info?msg=该牛人不存在，请不要不合理操作");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    if (!string.IsNullOrEmpty(model.Password))
                    {
                        if (!user.Password.Equals(Helpers.Encryt.GetMD5(model.Password)))
                        {
                            return Redirect("/Shared/Info?msg=" + "您输入原始密码错误！");
                        }
                        else
                        {
                            try
                            {
                                user.Password = Helpers.Encryt.GetMD5(model.PasswordNew);
                                db.SaveChanges();
                                return RedirectToAction("UserShow/" + user.ID);
                            }
                            catch (Exception ex)
                            {
                                log.Error(new LogContent("牛人密码修改出错", HttpHelper.GetIPAddress()), ex);
                                ModelState.AddModelError("", "保存修改信息出现错误，请重试!");
                            }
                        }
                    }
                    else
                    {
                        return RedirectToAction("UserShow/" + user.ID);
                    }
                }
                else
                {
                    ModelState.AddModelError("", "修改的信息输入错误!");
                }
                ViewBag.user = new vPwdEdit(user);
                return View();
            }
        }
        #endregion

        #region 牛人头像修改
        /// <summary>
        /// 牛人头像修改页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        [Schemas.AccessUserGroupEditUser]
        public ActionResult UserPictureEdit(int id)
        {
            User user = new User();
            user = db.Users.Find(id);
            if (user == null)
            {
                return Redirect("/Shared/Info?msg=该牛人不存在，请不要不合理操作");
            }
            else
            {
                ViewBag.User = user;
                ViewBag.UserGroup = db.UserGroups.Find(user.UserGroupID);
                return View();
            }
        }
        /// <summary>
        /// 牛人头像修改
        /// </summary>
        /// <param name="model"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        [Schemas.AccessUserGroupEditUser]
        public ActionResult UserPictureEdit(User model, int id, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                User user = db.Users.Find(model.ID);
                if (user == null)
                {
                    return Redirect("/Shared/Info?msg=该牛人不存在，请不要不合理操作");
                }
                else
                {
                    try
                    { if (file != null)
                    {
                        System.IO.Stream stream = file.InputStream;
                        byte[] buffer = new byte[stream.Length];
                        stream.Read(buffer, 0, (int)stream.Length);
                        stream.Close();
                        model.Picture = buffer;
                        user.Picture = model.Picture;
                    }
                    else
                    {
                        user.Picture = model.Picture;
                    }
                    db.SaveChanges();
                    return RedirectToAction("UserShow/" + user.ID);}
                    catch(Exception ex)
                    {
                        log.Error(new LogContent(" 牛人头像修改出错", HttpHelper.GetIPAddress()), ex);
                        return Redirect("/UserGroup/UserPictureEdit/" + model.ID);
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "图片信息存在问题，请审核后重新修改！");
            }
            ViewBag.User = db.Users.Find(model.ID);
            ViewBag.UserGroup = db.UserGroups.Find(model.UserGroupID);
            return View();
        }
        #endregion

        #region 牛棚展示页面
        /// <summary>
        /// 牛棚展示页面
        /// </summary>
        /// <returns></returns>
        [CustomException]
        public ActionResult UserGroupShow(int? id)
        {

            UserGroup group = db.UserGroups.Find(id);
            if (group == null)
            {
                return Redirect("/Shared/Info?msg=该牛棚不存在，请不要不合理操作");
            }
            else
            {
                try
                {
                    group.PV = group.PV + 1;
                    group.TodayPV = group.TodayPV + 1;
                    db.SaveChanges();
                    vUserGroup user = new vUserGroup(group);
                    ViewBag.User = user;
                    var u = "";
                    if (user.GroupName == null)
                    {
                        u = user.LoginName;
                    }
                    else
                    {
                        u = user.GroupName;
                    }
                    if (CurrentUser != null)
                    {
                        BrowseRecord browserecord = new BrowseRecord();
                        string url = Request.Url.ToString();
                        browserecord = db.BrowseRecords.Where(br => br.URL == url && br.UserID == CurrentUser.ID).FirstOrDefault();
                        if (browserecord == null)
                        {
                            BrowseRecord addbrowserecord = new BrowseRecord();
                            addbrowserecord.UserID = CurrentUser.ID;
                            addbrowserecord.URL = url;
                            addbrowserecord.Title = "牛棚展示——" + u;
                            addbrowserecord.Time = DateTime.Now;

                            db.BrowseRecords.Add(addbrowserecord);
                            db.SaveChanges();
                        }
                        else
                        {
                            db.BrowseRecords.Remove(browserecord);
                            BrowseRecord updatebrowserecord = new BrowseRecord();
                            updatebrowserecord.UserID = CurrentUser.ID;
                            updatebrowserecord.URL = url;
                            updatebrowserecord.Title = "牛棚展示——" + u;
                            updatebrowserecord.Time = DateTime.Now;

                            db.BrowseRecords.Add(updatebrowserecord);
                            db.SaveChanges();

                        }
                        var collect = db.Collects.Where(c => c.CollectTypeAsInt == 1 && c.TID == id && c.UserID == CurrentUser.ID).FirstOrDefault();
                        if (collect == null)
                        {
                            ViewBag.IsCollected = false;
                        }
                        else
                        {
                            ViewBag.IsCollected = true;
                        }
                    }
                    else
                    {
                        ViewBag.IsCollected = false;
                    }
                    return View();
                }
                catch(Exception ex)
                {
                    log.Error(new LogContent(" 牛人头像修改出错", HttpHelper.GetIPAddress()), ex);
                    return Redirect("/UserGroup/UserGroupShow/" + id);
                }
            }
        }
        /// <summary>
        /// 获取商户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowUserGroupList()
        {
            List<UserGroup> group_list = db.UserGroups.ToList();
            return Json(group_list);
        }
        #endregion

        #region 赞
        /// <summary>
        /// 赞
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateSID]
        public ActionResult Up(int id)
        {
            AjaxModel ajaxModel = new AjaxModel();
            var user = db.UserGroups.Find(id);
            if(user==null)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "赞失败！";
            }
            else
            {
                try {
                    user.Ups = user.Ups + 1;
                    db.SaveChanges();
                    ajaxModel.Statu = "ok";
                    ajaxModel.Msg = "赞成功！";
                }
                catch(Exception ex)
                {
                    log.Error(new LogContent(" 牛棚展示赞出错", HttpHelper.GetIPAddress()), ex);
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "赞失败！";
                }
            }
            return Json(ajaxModel);
        }
        #endregion


        #region 踩
        /// <summary>
        /// 赞
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        [ValidateSID]
        public ActionResult Down(int id)
        {
            AjaxModel ajaxModel = new AjaxModel();
            var user = db.UserGroups.Find(id);
            if (user == null)
            {
                ajaxModel.Statu = "err";
                ajaxModel.Msg = "踩失败！";
            }
            else
            {
                try
                {
                    user.Downs = user.Downs + 1;
                    db.SaveChanges();
                    ajaxModel.Statu = "ok";
                    ajaxModel.Msg = "踩成功！";
                }
                catch (Exception ex)
                {
                    log.Error(new LogContent(" 牛棚展示踩出错", HttpHelper.GetIPAddress()), ex);
                    ajaxModel.Statu = "err";
                    ajaxModel.Msg = "踩失败！";
                }
            }
            return Json(ajaxModel);
        }
        #endregion



        #region 增加收藏
        /// <summary>
        /// 增加收藏
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult AddCollect(int id)
        {
            AjaxModel model = new AjaxModel();
            Collect collect = new Collect();

            try
            {
                collect = db.Collects.Where(u => u.TID == id && u.UserID == CurrentUser.ID && u.CollectTypeAsInt == 1).FirstOrDefault();
                if (collect == null)
                {
                    collect = new Collect();
                    collect.CollectType = CollectType.UserGroup;
                    collect.UserID = CurrentUser.ID;
                    collect.TID = id;
                    collect.Time = DateTime.Now;
                    collect.CollectTypeAsInt = 1;
                    db.Collects.Add(collect);
                    db.SaveChanges();
                    model.Statu = "ok";
                }
                else
                {
                    model.Statu = "err";
                    model.Msg = "该牛棚已收藏！";
                }
            }
            catch (Exception ex)
            {
                log.Error(new LogContent(" 牛棚增加收藏出错", HttpHelper.GetIPAddress()), ex);
                model.Statu = "err";
                model.Msg = "收藏失败！";
            }
            return Json(model);
        }

        #endregion
        #region
        /// <summary>
        /// 取消收藏
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateSID]
        public ActionResult CancelCollect(int id)
        {
            AjaxModel model = new AjaxModel();
            Collect collect = new Collect();

            try
            {
                collect = db.Collects.Where(u => u.TID == id && u.UserID == CurrentUser.ID && u.CollectTypeAsInt == 1).FirstOrDefault();
                if (collect != null)
                {
                    db.Collects.Remove(collect);
                    db.SaveChanges();
                    model.Statu = "ok";
                }
                else
                {
                    model.Statu = "err";
                    model.Msg = "未收藏！";
                }
            }
            catch (Exception ex)
            {
                log.Error(new LogContent(" 牛棚取消收藏出错", HttpHelper.GetIPAddress()), ex);
                model.Statu = "err";
                model.Msg = "收藏失败！";
            }
            return Json(model);
        }
        #endregion
    }
}